/**
 * Created by Dell on 2017/5/9.
 */
'use strict';
var pg = require('../lib/pgClient');
const log = require('log4js').getLogger("models/project");
const async = require('async');
let sqlStart = "START TRANSACTION;";
let sqlRollback = "ROLLBACK;";
let sqlCommit = "COMMIT;";

/**
 * 后台添加项目
 * @param params
 * @param callback
 */
const add_sql1 = 'INSERT INTO project (name, logo, "desc", status, createtime) VALUES ($1, $2, $3, $4, $5)';//添加项目
const add_sql2 = 'SELECT * FROM project WHERE name = $1';//查找同名项目
exports.add_project = function(params, callback){
    const params2 = [
        params[0]//名称
    ];
    pg.query(add_sql2, params2, function(err, result){//执行查询操作（排重）
        if(err){
            callback (err, null);
        }else if(result.rowCount>0){
            callback (err, 'exit_name');//重名
        }else{
            pg.query(add_sql1, params, function(err, result){//执行添加操作
                if(err){
                    callback (err, null);
                }else if(result.rowCount == 0){
                    callback (err, 'fail');//失败
                }else{
                    callback (err, result);
                }
            })
        }
    })
};
/**
 * 后台设置图片关联项目（项目关联图片）
 * @param params
 * @param callback
 */
const relate_sql1 = 'SELECT * FROM picture WHERE id = $1 AND del = $2';//查找有没有这个图片；
const relate_sql2 = 'SELECT * FROM project WHERE id = $1 AND status = $2 ';//查找有没有这个项目；
const relate_sql3 = 'SELECT id FROM projestlogs WHERE pictureid = $1';//图片是否已经达到上限
const relate_sql6 = 'SELECT id FROM projestlogs WHERE pictureid = $1 AND projectid = $2';//图片是否已经与该项目关联
// const relate_sql4 = 'SELECT id FROM projestlogs WHERE projectid = $1';//项目是否已经达到上限（项目可以无限制关联图片）
const relate_sql5 = 'INSERT INTO projestlogs (pictureid, projectid, createtime) VALUES ($1, $2, $3)';//添加记录
exports.picture_project = function(params, callback){
    let info = []
    const params1 = [
        params[0],//图片id
        1
    ];
    const params2 = [
        params[0]//项目id
    ];
    const params3 = [
        params[1],//项目id
        1
    ];
    const params4 = [
        params[0],//图片id
        params[1]//项目id
    ];
    pg.query(relate_sql1, params1, function(err, result){//执行查找图片操作
        if(err){
            callback (err, null);
        }else if(result.rowCount==0){
            callback (err, 'null_picture')//没有图片
        }else {
            info.push(result.rows[0].name);//图片名称
            pg.query(relate_sql2, params3, function(err, result){//执行查找项目操作
                if(err){
                    callback (err, null);
                }else if(result.rowCount==0){
                    callback (err, 'null_project')//没有项目
                }else {
                    info.push(result.rows[0].name);//项目名称
                    pg.query(relate_sql3, params2, function(err, result){//执行查找记录中的图片次数
                        if(err){
                            callback (err, null);
                        }else if(result.rowCount>=5){
                            callback (err, 'too_much_picture')//关联的图片已经达到上限
                        }else {
                            // pg.query(relate_sql4, params2, function(err, result){//执行查找记录中的图片次数
                            //     if(err){
                            //         callback (err, null);
                            //     }else if(result.rowCount>=5){
                            //         callback (err, 'too_much_project')//关联的项目已经达到上限
                            //     }else {
                                    pg.query(relate_sql6, params4, function(err, result){//执行查询是否已关联操作
                                        if(err){
                                            callback (err, null);
                                        }else if(result.rowCount>0){
                                            callback (err, 'exit')//已经关联
                                        }else {
                                            pg.query(relate_sql5, params, function(err, result){//执行添加记录操作
                                                if(err){
                                                    callback (err, null);
                                                }else if(result.rowCount==0){
                                                    callback (err, 'fail')//执行添加操作失败
                                                }else {
                                                    callback (err, info);//返回含有图片名和项目名的信息
                                                }
                                            });
                                        }
                                    });
                            //     }
                            // });
                        }
                    });
                }
            });
        }
    });
};
/**
 * 后台设置图片关联项目（项目关联图片）
 * @param params
 * @param callback
 */
const unrelate_sql1 = 'SELECT * FROM picture WHERE id = $1 AND del = $2';//查找有没有这个图片；
const unrelate_sql2 = 'SELECT * FROM project WHERE id = $1';//查找有没有这个项目；
const unrelate_sql6 = 'SELECT id FROM projestlogs WHERE pictureid = $1 AND projectid = $2';//图片是否已经与该项目关联
const unrelate_sql5 = 'DELETE FROM projestlogs WHERE pictureid = $1 AND projectid = $2';//删除记录
exports.unpicture_project = function(params, callback){
    let info = []
    const params1 = [
        params[0],//图片id
        1
    ];
    const params3 = [
        params[1],//项目id
    ];
    pg.query(unrelate_sql1, params1, function(err, result){//执行查找图片操作
        if(err){
            callback (err, null);
        }else if(result.rowCount==0){
            callback (err, 'null_picture')//没有图片
        }else {
            info.push(result.rows[0].name);//图片名称
            pg.query(unrelate_sql2, params3, function(err, result){//执行查找项目操作
                if(err){
                    callback (err, null);
                }else if(result.rowCount==0){
                    callback (err, 'null_project')//没有项目
                }else {
                    info.push(result.rows[0].name);//项目名称
                    pg.query(unrelate_sql6, params, function(err, result){//执行查询是否已关联操作
                        if(err){
                            callback (err, null);
                        }else if(result.rowCount==0){
                            callback (err, 'exit')//未关联
                        }else {
                            pg.query(unrelate_sql5, params, function(err, result){//执行添加记录操作
                                if(err){
                                    callback (err, null);
                                }else if(result.rowCount==0){
                                    callback (err, 'fail')//执行添加操作失败
                                }else {
                                    callback (err, info);//返回含有图片名和项目名的信息
                                }
                            });
                        }
                    });
                }
            });
        }
    });
};
/**
 * 后台设置品牌关联项目（项目关联品牌）
 * @param params
 * @param callback
 */
const relate_brand_sql1 = 'SELECT * FROM brand WHERE id = $1 AND status = $2 AND grand = $3';//查找有没有这个品牌；
const relate_brand_sql2 = 'SELECT * FROM project WHERE id = $1 AND status = $2 ';//查找有没有这个项目；
const relate_brand_sql3 = 'SELECT id FROM brand_project WHERE brandid = $1';//品牌是否已经达到上限
const relate_brand_sql6 = 'SELECT id FROM brand_project WHERE brandid = $1 AND projectid = $2';//品牌是否已经与该项目关联
const relate_brand_sql4 = 'SELECT id FROM brand_project WHERE projectid = $1';//项目是否已经达到上限(一个项目可以添加5个二级品牌)
const relate_brand_sql5 = 'INSERT INTO brand_project (brandid, projectid, createtime) VALUES ($1, $2, $3)';//添加记录
exports.brand_project = function(params, callback){
    let info = []
    const params1 = [
        params[0],//图片id
        1,//正常状态
        2//二级分类
    ];
    const params5 = [
        params[0],//图片id
    ];
    const params2 = [
        params[1]//项目id
    ];
    const params3 = [
        params[1],//项目id
        1
    ];
    const params4 = [
        params[0],//图片id
        params[1]//项目id
    ];
    pg.query(relate_brand_sql1, params1, function(err, result){//执行查找图片操作
        if(err){
            callback (err, null);
        }else if(result.rowCount==0){
            callback (err, 'null_brand')//没有品牌
        }else {
            info.push(result.rows[0].name);//品牌名称
            pg.query(relate_brand_sql2, params3, function(err, result){//执行查找项目操作
                if(err){
                    callback (err, null);
                }else if(result.rowCount==0){
                    callback (err, 'null_project')//没有项目
                }else {
                    info.push(result.rows[0].name);//项目名称
                    pg.query(relate_brand_sql3, params5, function(err, result){//执行查找记录中的品牌次数
                        if(err){
                            callback (err, null);
                        }else if(result.rowCount>=5){
                            callback (err, 'too_much_brand')//关联的品牌已经达到上限
                        }else {
                            pg.query(relate_brand_sql4, params2, function(err, result){//执行查找记录中的品牌次数
                                if(err){
                                    callback (err, null);
                                }else if(result.rowCount>=5){
                                    callback (err, 'too_much_project')//关联的项目已经达到上限
                                }else {
                                    pg.query(relate_brand_sql6, params4, function(err, result){//执行查询是否已关联操作
                                        if(err){
                                            callback (err, null);
                                        }else if(result.rowCount>0){
                                            callback (err, 'exit')//已经关联
                                        }else {
                                            pg.query(relate_brand_sql5, params, function(err, result){//执行添加记录操作
                                                if(err){
                                                    callback (err, null);
                                                }else if(result.rowCount==0){
                                                    callback (err, 'fail')//执行添加操作失败
                                                }else {
                                                    callback (err, info);//返回含有品牌名和项目名的信息
                                                }
                                            });
                                        }
                                    });
                                }
                            });
                        }
                    });
                }
            });
        }
    });
};
/**
 * 后台设置品牌关联项目（项目关联品牌）
 * @param params
 * @param callback
 */
const unrelate_brand_sql1 = 'SELECT * FROM brand WHERE id = $1';//查找有没有这个品牌；
const unrelate_brand_sql2 = 'SELECT * FROM project WHERE id = $1';//查找有没有这个项目；
const unrelate_brand_sql6 = 'SELECT id FROM brand_project WHERE brandid = $1 AND projectid = $2';//品牌是否已经与该项目关联
const unrelate_brand_sql5 = 'DELETE FROM brand_project WHERE brandid = $1 AND projectid = $2';//添加记录
exports.unbrand_project = function(params, callback){
    let info = []
    const params1 = [
        params[0]//图片id
    ];
    const params2 = [
        params[1]//项目id
    ];
    pg.query(unrelate_brand_sql1, params1, function(err, result){//执行查找图片操作
        if(err){
            callback (err, null);
        }else if(result.rowCount==0){
            callback (err, 'null_brand')//没有品牌
        }else {
            info.push(result.rows[0].name);//品牌名称
            pg.query(unrelate_brand_sql2, params2, function(err, result){//执行查找项目操作
                if(err){
                    callback (err, null);
                }else if(result.rowCount==0){
                    callback (err, 'null_project')//没有项目
                }else {
                    info.push(result.rows[0].name);//项目名称
                    pg.query(unrelate_brand_sql6, params, function(err, result){//执行查询是否已关联操作
                        if(err){
                            callback (err, null);
                        }else if(result.rowCount==0){
                            callback (err, 'exit')//已经关联
                        }else {
                            pg.query(unrelate_brand_sql5, params, function(err, result){//执行添加记录操作
                                if(err){
                                    callback (err, null);
                                }else if(result.rowCount==0){
                                    callback (err, 'fail')//执行添加操作失败
                                }else {
                                    callback (err, info);//返回含有品牌名和项目名的信息
                                }
                            });
                        }
                    });
                }
            });
        }
    });
};
/**
 *后台多条件查询项目列表
 * @param params
 * @param args
 * @param callback
 */
exports.list_b = function(params, args, callback){
    let sql = 'SELECT * FROM project WHERE 1=1';//查询
    let number = 1;
    if(args.status&&args.status!='all'){//状态
        sql +=' AND status = $'+number;
        number++;
    }
    if(args.keyword){//关键字模糊查询
        sql +=' AND (name like $'+number+' OR "desc" like $'+number+')';
        number++;
    }
    sql +=' ORDER BY createtime DESC LIMIT $'+number+' OFFSET $'+(number+1);//分页
    pg.query(sql, params, function(err, result){//执行操作
        if(err){
            callback (err, null);//报错
        }else {
            callback (err, result);//返回信息
        }
    });
};

/**
 *后台多条件查询项目列表数据统计
 * @param params
 * @param args
 * @param callback
 */
exports.count_b = function(params, args, callback){
    let sql = 'SELECT count(*) FROM project WHERE 1=1';//查询
    let number = 1;
    if(args.status&&args.status!='all'){//状态
        sql +=' AND status = $'+number;
        number++;
    };
    if(args.keyword){//关键字模糊查询
        sql +=' AND (name like $'+number+' OR "desc" like $'+number+')';
        number++;
    } ;
    pg.query(sql, params, function(err, result){//执行操作
        if(err){
            callback (err, null);//报错
        }else {
            callback (err, result);//返回信息
        }
    });
};
/**
 * 图片关联项目列表
 * @param args
 * @param callback
 */
const relate_list_picture_sql1 = 'SELECT projectid FROM projestlogs WHERE pictureid = $1';//查已经关联图片的项目的id
exports.relate_list_picture = function(args, params, callback){
    let params1 = [
        args.pictureid
    ];
    let ids = [];
    let sql = 'SELECT * FROM project WHERE id';
    pg.query(relate_list_picture_sql1, params1, function(err, result){
        if(err){
            callback (err, null);
        }else{
            if(result.rowCount == 0){
                ids.push(0);
            }else {
                let rows = result.rows;
                rows.forEach(function(row){
                    ids.push(row.projectid)
                })
            }
            let theids = "'"+ids.join("','")+"'";//将数组转化为字符串
            log.debug(theids);
            if(args.type == 'related'){//已关联
                sql += ' in ('+theids+') ORDER BY createtime DESC LIMIT $1 OFFSET $2';
            }else{//未关联
                sql += ' not in ('+theids+') AND status = $3 ORDER BY createtime DESC LIMIT $1 OFFSET $2';
            }
            pg.query(sql, params, function(err, result){//执行查询操作
                if(err){
                    callback (err, null);
                }else {
                    callback (err, result);
                }
            });
        }
    });
};

/**
 * 图片关联项目列表
 * @param args
 * @param callback
 */
const relate_list_picture_app_sql1 = 'SELECT pictureid FROM projestlogs WHERE projectid = $1';//查已经关联图片的项目的id
const p_sql4 = 'SELECT * FROM wantlogs WHERE userid = $1 AND type = $2 AND pid = $3';
const p_sql5 = 'SELECT * FROM ownlogs WHERE userid = $1 AND type = $2 AND pid = $3';
exports.relate_list_picture_app = function(args, params, req, callback){
    let date1 =  new Date().getTime();
    let date2 = new Date(date1 - 1000 * 60 * 60 * 6);//6小时之内
    let params1 = [
        args.projectid
    ];
    let ids = [];
    var info;
    let infos = [];
    let sql = 'SELECT * FROM picture WHERE id';
    pg.query(relate_list_picture_app_sql1, params1, function(err, result){
        if(err){
            callback (err, null);
        }else{
            if(result.rowCount == 0){
                ids.push(0);
            }else {
                let rows = result.rows;
                rows.forEach(function(row){
                    ids.push(row.pictureid)
                })
            }
            let theids = "'"+ids.join("','")+"'";//将数组转化为字符串
            log.debug(theids);
            sql += ' in ('+theids+') ORDER BY pushtime DESC LIMIT $1 OFFSET $2';
            pg.query(sql, params, function(err, result){//执行查询操作
                if(err){
                    callback (err, null);
                }else {
                    const sqlwant = 'SELECT w.createtime, w.userid, u.headurl FROM wantlogs w, users u WHERE w.userid=u.id AND w.pid = $1 AND w.createtime > $2 AND w.type = $3 ORDER BY w.createtime DESC LIMIT 1 OFFSET 0';//查找想要记录中最后一次想要时间
                    let pictures = result.rows;
                    let len = pictures.length;
                    let a = 0;
                    if(len > 0 ){
                        pg.connect(function (err, client, done) { //获取数据库链接
                            client.query(sqlStart, function () { //开启事务
                                async.mapSeries(pictures,function (picture,callback) {
                                        let paramswant = [
                                            picture.id,
                                            date2,
                                            1
                                        ];
                                        log.debug(paramswant);
                                        const params4 = [
                                            req.user.id,
                                            1,
                                            picture.id
                                        ]
                                        client.query(sqlwant, paramswant, function (err, result) {//想要记录
                                            if (err) {
                                                callback(err, result);
                                            } else if (result.rowCount == 0) {
                                                let last_time = null;
                                                let headurl = null;
                                                client.query(p_sql4, params4, function (err, result) {//想要人数
                                                    if (err) {
                                                        callback(err, result);
                                                    } else {
                                                        let u_want = 0;
                                                        u_want = result.rowCount;
                                                        client.query(p_sql5, params4, function (err, result) {//拥有人数
                                                            if (err) {
                                                                callback(err, result);
                                                            } else {
                                                                let u_own = result.rowCount;
                                                                info = {
                                                                    id: picture.id,
                                                                    name: picture.name,
                                                                    imgurl: picture.imgurl,
                                                                    desc: picture.desc,
                                                                    want: picture.want,
                                                                    own: picture.own,
                                                                    point: picture.point,
                                                                    author: picture.author,
                                                                    pushtime: picture.pushtime,
                                                                    username: picture.username,
                                                                    headurl: headurl,
                                                                    last_time: last_time,
                                                                    u_want: u_want,
                                                                    u_own: u_own
                                                                };
                                                                a++;
                                                                infos.push(info);
                                                                if (a == len) {
                                                                    callback(err, info);//结果
                                                                }
                                                                ;
                                                            }
                                                        })
                                                    }
                                                })
                                            } else {
                                                let last_time = result.rows[0].createtime;
                                                let headurl = result.rows[0].headurl;
                                                client.query(p_sql4, params4, function (err, result) {//想要人数
                                                    if (err) {
                                                        callback(err, result);
                                                    } else {
                                                        let u_want = 0;
                                                        u_want = result.rowCount;
                                                        client.query(p_sql5, params4, function (err, result) {//拥有人数
                                                            if (err) {
                                                                callback(err, result);
                                                            } else {
                                                                let u_own = result.rowCount;
                                                                info = {
                                                                    id: picture.id,
                                                                    name: picture.name,
                                                                    imgurl: picture.imgurl,
                                                                    desc: picture.desc,
                                                                    want: picture.want,
                                                                    own: picture.own,
                                                                    point: picture.point,
                                                                    author: picture.author,
                                                                    pushtime: picture.pushtime,
                                                                    username: picture.username,
                                                                    headurl: headurl,
                                                                    last_time: last_time,
                                                                    u_want: u_want,
                                                                    u_own: u_own
                                                                };
                                                                a++;
                                                                infos.push(info);
                                                                if (a == len) {
                                                                    callback(err, info);//结果
                                                                }
                                                                ;
                                                            }
                                                        })
                                                    }
                                                })
                                            }
                                        });
                                    },
                                    function (err, n) { //循环完毕提交事务
                                        if (err) {
                                            log.error(err);
                                            log.error('回滚.............');
                                            client.query(sqlRollback, function (errRollback) {
                                                if (errRollback) {
                                                    log.error('回滚失败');
                                                    log.error(errRollback);
                                                }
                                                done();
                                                callback(errRollback, null);
                                            });
                                        } else {
                                            log.debug('提交.............');
                                            client.query(sqlCommit, function (errCommit) {
                                                if (errCommit) {
                                                    client.query(sqlRollback, function (errRollback) {
                                                        if (errRollback) {
                                                            console.log('回滚失败');
                                                            log.error(errRollback);
                                                        }
                                                        done(); //关闭链接
                                                        callback(errCommit, infos);
                                                    });
                                                } else {
                                                    done();
                                                    callback(errCommit, infos);
                                                }

                                            });
                                        }
                                    })
                            })
                        })

                    }else {
                        callback (err, infos);//没作品
                    }

                }
            });
        }
    });
};
/**
 * 图片关联项目列表数据统计
 * @param args
 * @param callback
 */
const relate_count_picture_sql1 = 'SELECT projectid FROM projestlogs WHERE pictureid = $1';//查已经关联图片的项目的id
exports.relate_count_picture = function(args, params,  callback){
    let params1 = [
        args.pictureid
    ];
    let ids = [];
    let sql = 'SELECT count(*) FROM project WHERE id';
    pg.query(relate_count_picture_sql1, params1, function(err, result){
        if(err){
            callback (err, null);
        }else{
            if(result.rowCount == 0){
                ids.push(0);
            }else {
                let rows = result.rows;
                rows.forEach(function(row){
                    ids.push(row.projectid)
                })
            }
            let theids = "'"+ids.join("','")+"'";//将数组转化为字符串
            log.debug(theids);
            if(args.type == 'related'){//已关联
                sql += ' in ('+theids+')';
            }else{//未关联
                sql += ' not in ('+theids+') AND status = $1';
            }
            pg.query(sql, params, function(err, result){//执行查询操作
                if(err){
                    callback (err, null);
                }else {
                    callback (err, result);
                }
            });
        }
    });
};

/**
 * 图片关联项目列表
 * @param args
 * @param callback
 */
const relate_list_brand_sql1 = 'SELECT projectid FROM brand_project WHERE brandid = $1';//查已经关联图片的项目的id
exports.relate_list_brand = function(args, params, callback){
    let params1 = [
        args.brandid
    ];
    let ids = [];
    let sql = 'SELECT * FROM project WHERE id';
    pg.query(relate_list_brand_sql1, params1, function(err, result){
        if(err){
            callback (err, null);
        }else{
            if(result.rowCount == 0){
                ids.push(0);
            }else {
                let rows = result.rows;
                rows.forEach(function(row){
                    ids.push(row.projectid)
                })
            }
            let theids = "'"+ids.join("','")+"'";//将数组转化为字符串
            log.debug(theids);
            if(args.type == 'related'){//已关联
                sql += ' in ('+theids+') ORDER BY createtime DESC LIMIT $1 OFFSET $2';
            }else{//未关联
                sql += ' not in ('+theids+') AND status = $3 ORDER BY createtime DESC LIMIT $1 OFFSET $2';
            }
            pg.query(sql, params, function(err, result){//执行查询操作
                if(err){
                    callback (err, null);
                }else {
                    callback (err, result);
                }
            });
        }
    });
};
/**
 * 图片关联项目列表数据统计
 * @param args
 * @param callback
 */
const relate_count_brand_sql1 = 'SELECT projectid FROM brand_project WHERE brandid = $1';//查已经关联图片的项目的id
exports.relate_count_brand = function(args, params,  callback){
    let params1 = [
        args.brandid
    ];
    let ids = [];
    let sql = 'SELECT count(*) FROM project WHERE id';
    pg.query(relate_count_brand_sql1, params1, function(err, result){
        if(err){
            callback (err, null);
        }else{
            if(result.rowCount == 0){
                ids.push(0);
            }else {
                let rows = result.rows;
                rows.forEach(function(row){
                    ids.push(row.projectid)
                })
            }
            let theids = "'"+ids.join("','")+"'";//将数组转化为字符串
            log.debug(theids);
            if(args.type == 'related'){//已关联
                sql += ' in ('+theids+')';
            }else{//未关联
                sql += ' not in ('+theids+') AND status = $1';
            }
            pg.query(sql, params, function(err, result){//执行查询操作
                if(err){
                    callback (err, null);
                }else {
                    callback (err, result);
                }
            });
        }
    });
};

/**
 *批量删除项目信息
 */
exports.remove = function(args, callback){
    let ids = args.ids;//ids 是数组
    let theids = "'"+ids.join("','")+"'";//将数组ids整理成字符串
    const remove_sql1 = 'DELETE FROM project WHERE id IN ('+theids+')';//删除id在theids的项目数据
    const remove_sql2 = 'SELECT id FROM project WHERE id IN ('+theids+')';//查询id在theids的项目数据
    const remove_sql3 = 'DELETE FROM projestlogs WHERE projectid IN ('+theids+')';//查询id在theids的项目图片关联数据
    const remove_sql4 = 'DELETE FROM brand_project WHERE projectid IN ('+theids+')';//查询id在theids的项目品牌关联数据
    pg.query(remove_sql2, [], function(err,result){//执行查询操作
        if(err){
            callback (err,null);
        }else if(result.rowCount == 0) {//项目不存在
            callback (err,null);
        }else{
            pg.connect(function (err, client, done) {
                client.query(sqlStart, function () {
                    client.query(remove_sql1, [], function (err, result) {//查作者
                        if (err) {
                            log.error(err);
                            client.query(sqlRollback, function (errRollback) {
                                if (errRollback) {
                                    log.error('删除项目报错');
                                }
                                done();
                                callback(err, null);
                            })
                        } else if (result.rowCount == 0) {
                            log.error('删除项目失败');
                            client.query(sqlRollback, function (errRollback) {
                                if (errRollback) {
                                    log.error('删除项目失败');
                                }
                                done();
                                return callback(err,'null');
                            })
                        } else {
                            client.query(remove_sql3, [], function (err, result) {//查分类
                                if (err) {
                                    log.error(err);
                                    client.query(sqlRollback, function (errRollback) {
                                        if (errRollback) {
                                            log.error('删除关联记录失败');
                                        }
                                        done();
                                        callback(err, null);
                                    })
                                } else {
                                    client.query(remove_sql4, [], function (err, result) {//删除项目品牌关联
                                        if (err) {//失败
                                            log.error(err);
                                            client.query(sqlRollback, function (errRollback) {
                                                if (errRollback) {
                                                    log.error('删除项目品牌关联失败');
                                                }
                                                done();
                                                callback(err,null);
                                            });
                                        } else {
                                            client.query(sqlCommit, function (errCommit) {
                                                if (errCommit) {
                                                    client.query(sqlRollback, function (errRollback) {
                                                        if (errRollback) {
                                                            log.error('回滚失败');
                                                        }
                                                        done();
                                                        callback(err, null);
                                                    });
                                                } else {
                                                    done();
                                                    return callback(err, result);//删除成功
                                                }
                                            });
                                        }
                                    });
                                }
                            })

                        }
                    });
                });
            })
        };
    });
};


/**
 * 批量编辑项目状态
 */
exports.upd_status = function(args, callback){
    let ids = args.ids;//ids 是数组
    let theids = "'"+ids.join("','")+"'";//将数组ids整理成字符串
    const upd_sql = 'UPDATE project SET status = $1 WHERE id IN ('+theids+')';//编辑id在theids的项目数据
    const params =[
        args.status
    ]
    pg.query(upd_sql, params, function(err,result){//执行编辑操作
        if(err){//报错
            callback (err,null);
        }else {
            callback (err,result);//执行结束
        }
    });
};

/**
 *  后台品牌关联图片（已关联和未关联列表）
 * @param params
 * @param args
 * @param callback
 */
const picture_list_sql1 = 'SELECT * FROM projestlogs WHERE projectid = $1';//已关联图片记录
exports.picture_list = function(params, args, callback){
    const params1 = [
        args.projectid
    ];
    let ids = [];
    let sql = 'SELECT id, name, imgurl FROM picture WHERE id';
    pg.query(picture_list_sql1, params1, function(err, result){
        if(err){
            callback (err, null);
        }else{
            if(result.rowCount == 0){
                ids.push(0);
            }else {
                let rows = result.rows;
                rows.forEach(function(row){
                    ids.push(row.pictureid)
                })
            }
            let theids = "'"+ids.join("','")+"'";//将数组转化为字符串
            log.debug(theids);
            if(args.type == 'related'){//已关联
                sql += ' in ('+theids+') ORDER BY pushtime DESC LIMIT $1 OFFSET $2';
            }else{//未关联
                sql += ' not in ('+theids+') AND status = $3 AND del = $4 ORDER BY pushtime DESC LIMIT $1 OFFSET $2';
            }
            pg.query(sql, params, function(err, result){//执行查询操作
                if(err){
                    callback (err, null);
                }else {
                    callback (err, result);
                }
            });
        }
    });
};
/**
 *  后台品牌关联图片（已关联和未关联列表）
 * @param params
 * @param args
 * @param callback
 */
const picture_count_sql1 = 'SELECT * FROM projestlogs WHERE projectid = $1';//已关联图片记录
exports.picture_count = function(params, args, callback){
    const params1 = [
        args.projectid
    ];
    let ids = [];
    let sql = 'SELECT count(*) FROM picture WHERE id';
    pg.query(picture_count_sql1, params1, function(err, result){
        if(err){
            callback (err, null);
        }else{
            if(result.rowCount == 0){
                ids.push(0);
            }else {
                let rows = result.rows;
                rows.forEach(function(row){
                    ids.push(row.pictureid)
                })
            }
            let theids = "'"+ids.join("','")+"'";//将数组转化为字符串
            log.debug(theids);
            if(args.type == 'related'){//已关联
                sql += ' in ('+theids+')';
            }else{//未关联
                sql += ' not in ('+theids+') AND status = $1 AND del = $2 ';
            }
            pg.query(sql, params, function(err, result){//执行查询操作
                if(err){
                    callback (err, null);
                }else {
                    callback (err, result);
                }
            });
        }
    });
};
/**
 * 项目详情
 * @param params
 * @param callback
 */
const info_sql = 'SELECT * FROM project WHERE id = $1';//根据id查项目详情
exports.info = function(params, callback){
    pg.query(info_sql, params, function(err, result){//执行查找操作
        if(err){
            callback (err, null);
        }else if(result.rowCount == 0){
            callback (err, 'null');//没有
        }else {
            callback (err, result);//返回信息
        }
    })
};
/**
 * 前后台编辑项目详情
 * @param params
 * @param callback
 */
const upd_info_sql1 = 'SELECT * FROM project WHERE id = $1';//是否有这个项目
const upd_info_sql2 = 'UPDATE project SET name = $1, logo = $2, "desc" = $3, status = $4 WHERE id = $5';//根据id编辑信息
exports.upd_info = function(params, callback){
    pg.query(upd_info_sql1, [params[4]], function(err, result){//是否有项目
        if(err){
            callback (err, null);
        }else if(result.rowCount == 0){
            callback (err, 'null');
        }else {
            let pro = result.rows[0];
            pg.query(upd_info_sql2, params, function(err,result){//编辑
                if(err){
                    callback (err, null);//报错
                }else if(result.rowCount == 0){
                    callback (err, 'fail');//报错
                }else{
                    callback (err, pro);//成功
                }
            })
        }
    })
};